package com.xuerhua.yxt.controller.sys.signup;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.xuerhua.yxt.common.AdminUser;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.common.enums.StudentSignUpType;
import com.xuerhua.yxt.common.enums.StudentSignupStaus;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.excel.CellUtil;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.StudentSignUp;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.SignupResultVO;
import com.xuerhua.yxt.service.IStudentSignUpService;
import com.xuerhua.yxt.utils.ExcelExportUtil;
import com.xuerhua.yxt.utils.ExportSetInfoUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.vo.SignUpQueryVO;

@RequestMapping("sys/signUp/middleStudent")
@Controller
public class SysMiddleStudentController extends BaseController
{

  @Autowired
  private IStudentSignUpService studentSignUpService;

  @RequestMapping(value = {"", "/"})
  public String index() {
    return "sys/signup/middleStudent";
  }

  @RequestMapping("print/{ids}")
  public String printById(@PathVariable String ids, Model model) {
    List<StudentSignUp> list = studentSignUpService.selectListByIds(StudentSignUpType.MIDDLE_STUDENT.getCode(), ids);
    model.addAttribute("list", list);
    model.addAttribute("signupType", StudentSignUpType.MIDDLE_STUDENT.getDesc());
    return "sys/signup/studentList";
  }

  @RequestMapping("print/list")
  public String printList(SignUpQueryVO vo, Model model) {
    vo.setSignUpType(StudentSignUpType.MIDDLE_STUDENT.getCode());
    Page<StudentSignUp> page = new Page<>();
    page.setParams(vo);
    page.setPageNo(vo.getPage());
    page.setPageSize(Integer.MAX_VALUE - 1);
    List<StudentSignUp> list = studentSignUpService.selectListByPage(page);
    model.addAttribute("list", list);
    model.addAttribute("signupType", StudentSignUpType.MIDDLE_STUDENT.getDesc());
    return "sys/signup/studentList";
  }
  @RequestMapping("pageQuery")
  @ResponseBody
  Object pageQuery(SignUpQueryVO vo) {
    try { vo.setSignUpType(StudentSignUpType.MIDDLE_STUDENT.getCode());
      Page<StudentSignUp> page = new Page<>();
      page.setParams(vo);
      page.setPageNo(vo.getPage());
      page.setPageSize(vo.getRows());
      List<StudentSignUp> list = studentSignUpService.selectListByPage(page);
      Grid grid = new Grid();
      grid.setRows(list);
      grid.setTotal(page.getTotalRecord());
      return grid;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  @RequestMapping("ok")
  @ResponseBody
  Object Ok(SignupResultVO record) {
    try { 
      record.setStatus("000");
      record.setSignupType(StudentSignUpType.MIDDLE_STUDENT.getCode());
      studentSignUpService.updateSignupResult(record);
      return new RspResult(Status.SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new RspResult(Status.FAIL);
  }
  @RequestMapping("no")
  @ResponseBody
  Object no(SignupResultVO record) {
    try { record.setStatus("002");
      record.setSignupType(StudentSignUpType.MIDDLE_STUDENT.getCode());
      studentSignUpService.updateSignupResult(record);
      return new RspResult(Status.SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new RspResult(Status.FAIL);
  }

  @RequestMapping("export")
  ModelAndView export(SignUpQueryVO vo) {
    ModelAndView modelAndView = new ModelAndView();
    try {
      vo.setSignUpType(StudentSignUpType.MIDDLE_STUDENT.getCode());
      Page<StudentSignUp> page = new Page<>();
      page.setParams(vo);
      page.setPageSize(Integer.MAX_VALUE - 1);
      List<StudentSignUp> list = studentSignUpService.selectListByPage(page);

      LinkedHashMap<String, List> map = new LinkedHashMap();
      String title = "插班生报名名单";
      map.put(title, list);

      List<String[]> headNames = new ArrayList<>();
      headNames.add(new String[] { "报名状态", "结果反馈", "报名号", "学生姓名", "联系电话", "学生性别", "生日", "证件类型", "证件号", "报读年级", "原就读学校", 
        "健康状况", "民族", "籍贯", "户籍所在地", "户籍所在镇街", "家庭地址", "爸爸姓名", "爸爸电话", "爸爸单位", "妈妈姓名", "妈妈电话", "妈妈单位", "是否参加开放日", "就读方式", "报名时间" });
      List<String[]> fieldNames = new ArrayList<>();
      fieldNames.add(new String[] { "statusText", "resultMessage", "signupNo", "studentName", "userPhone", "studentSex", "studentBirthday", "studentIdType", "studentIdNo", "signGrade", "baseSchool", 
        "healthy", "nation", "nativePlace", "houseSSQ", "houseAddr", "familyAddr", "fatherName", "fatherPhone", "fatherCompany", "motherName", "motherPhone", "motherCompany", "isJoinOpenday", "schoolStudyTypeText", "signUpTime" });

      String[] titles = { title };

      ExportSetInfoUtil setInfo = new ExportSetInfoUtil(map, titles, headNames, fieldNames, null);
      this.request.setAttribute("exportDatas", setInfo);

      modelAndView = new ModelAndView(new ExcelExportUtil(title + ".xls", ""));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return modelAndView;
  }

  @RequestMapping("import")
  @ResponseBody
  Object courseImport(@RequestParam("files") MultipartFile buildInfo) {
    try {
      InputStream inputStream = buildInfo.getInputStream();
      AdminUser adminUser = getAdminUser();
      Workbook wookbook = null;
      String filename = buildInfo.getOriginalFilename();
      String fileType = filename.substring(filename.lastIndexOf(".") + 1, 
        filename.length());
      if (fileType.equals("xls"))
        try {
          wookbook = new HSSFWorkbook(inputStream);
        } catch (Exception e) {
          wookbook = null;
          wookbook = new XSSFWorkbook(inputStream);
        }
      else {
        wookbook = new XSSFWorkbook(inputStream);
      }

      Sheet sheet = wookbook.getSheetAt(0);
      int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();
      int rowNum = sheet.getPhysicalNumberOfRows();
      if (rowNum <= 1) {
        return new RspResult(Status.TEMPLATE_DATA_NULL);
      }
      Map<Integer, String> map = new HashMap<>();
      Row headRow = sheet.getRow(0);
      for (int i = 0; i < coloumNum; i++) {
        Cell cell = headRow.getCell((short)i);
        String val = CellUtil.getCellValue(cell);
        if (StringUtils.isNotBlank(val)) {
          map.put(Integer.valueOf(i), StringUtil.removeSpecialChar(val));
        }
      }
      List<StudentSignUp> list = new ArrayList<>();
      List<String> errorList = new ArrayList<>();

      for (int i = 1; i < rowNum; i++)
      {
        Row row = sheet.getRow(i);

        if (row != null) {
          StudentSignUp plan = new StudentSignUp();
          List<String> error = new ArrayList<>();
          for (int j = 0; j < coloumNum; j++) {
            Cell cell = row.getCell((short)j);
            if (cell != null) {
              String val = CellUtil.getCellValue(cell);
              if (j == 0) {
                plan.setStatus(StudentSignupStaus.getCode(val));
                if (StringUtils.isBlank(plan.getStatus()))
                  error.add((String)map.get(Integer.valueOf(j)) + "值有误");
              }
              else if (j == 1) {
                plan.setResultMessage(val);
                if (StringUtils.isBlank(val))
                  error.add((String)map.get(Integer.valueOf(j)) + "不能为空");
              }
              else if (j == 2) {
                plan.setSignupNo(val);
                if (!StringUtils.isBlank(val)) break;
                error.add((String)map.get(Integer.valueOf(j)) + "不能为空");

                break;
              }
              plan.setSchoolId(adminUser.getTeacherInfo().getSchoolId());
            }
          }
          if (!StringUtil.isNullOrEmpty(error))
            errorList.add("第" + (i + 1) + "行" + String.join("/|", error));
          else {
            list.add(plan);
          }
        }
      }

      if (!StringUtil.isNullOrEmpty(errorList)) {
        return new RspResult(Status.FAIL.getCode(), String.join("，", errorList));
      }
      studentSignUpService.updateBatchSignupStatus(list);
      return new RspResult(Status.SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new RspResult(Status.TEMPLATE_ERROR);
  }
}